import requests
import json

def test_api():
    """测试Web API"""
    base_url = "http://localhost:8000"
    
    # 测试根页面
    print("=== 测试根页面 ===")
    try:
        response = requests.get(base_url)
        print(f"状态码: {response.status_code}")
        if response.status_code == 200:
            print("✅ 根页面访问成功")
        else:
            print(f"❌ 根页面访问失败: {response.text}")
    except Exception as e:
        print(f"❌ 根页面访问错误: {e}")
    
    # 测试SQLite数据库分析
    print("\n=== 测试SQLite数据库分析 ===")
    
    test_data = {
        "db_type": "sqlite",
        "database": "example_ecommerce.db"
    }
    
    try:
        response = requests.post(
            f"{base_url}/analyze",
            json=test_data,
            headers={"Content-Type": "application/json"}
        )
        
        print(f"状态码: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            print(f"✅ API调用成功")
            print(f"成功状态: {result.get('success')}")
            print(f"表数量: {len(result.get('tables', []))}")
            print(f"关系数量: {len(result.get('relationships', []))}")
            
            if result.get('tables'):
                print("\n表列表:")
                for table in result['tables']:
                    print(f"  - {table['name']}: {len(table['columns'])} 列")
            
            if result.get('relationships'):
                print("\n关系列表:")
                for rel in result['relationships']:
                    print(f"  - {rel['from_table']}.{rel['from_column']} -> {rel['to_table']}.{rel['to_column']}")
        else:
            print(f"❌ API调用失败")
            print(f"响应内容: {response.text}")
            
    except Exception as e:
        print(f"❌ API调用错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    test_api()